<template>
	<joy-page class="joyPage bg-gray">
		<cu-custom bgColor="bg-gradual-pink" :isBack="true">
			<block slot="backText"></block>
			<block slot="content">充值</block>
		</cu-custom>
		<view class="padding bg-white margin-bottom">
			<view class="cu-steps">
				<view class="cu-item" :class="index>basics?'text-invalid':'text-orange'" v-for="(item,index) in basicsList" :key="index">
					<text :class="'cuIcon-' + item.cuIcon"></text> <span class='step-text'>{{item.name}}</span>
				</view>
			</view>
			<view class="tips text-pink padding-top">尊敬的会员，受政策原因暂不支持信用卡！</view>
		</view>
		<view v-if="basics == 0">
			<view class="orderContent">
				<view class="info">
					<view class="bg-white margin-bottom padding-top-xs padding-bottom-sm">
						<view class="order-content">
							<m-input type="number" label='充值金额(元)' v-model="form.money" :maxLength="11" :focus="true"></m-input>
						</view>
						<view class="cu-form-group margin-top margin-bottom">
							<view class="title text-gray">银行卡</view>
							<picker @change="PickerChange" :value="index" :range="data" range-key='text'>
								<view class="picker">
									{{form.bankName}}
								</view>
							</picker>
						</view>
						<view class="text-red text-sm text-left paddingcontent" v-if="data.length === 0">*您尚未添加银行卡<text class="text-blue"
							 @tap="goPage('bankCard')">点击添加</text></view>
					</view>
					<view class="bg-white padding-top-xs padding-bottom-sm">
					<view class="order-content">
						<m-input type="number" label='支付金额(元)' disabled v-model="form.realMoney" :maxLength="11"></m-input>
					</view>
					<view class="order-content margin-bottom">
						<m-input type="password" label='支付密码' v-model="form.password" :maxLength="11"></m-input>
					</view>
					<view class="text-red text-sm text-left paddingcontent" v-if="!hasSetPayPhone">*您尚未设置认证手机<text class="text-blue"
						 @tap="goPage('certifiedPhone')">点击设置</text></view>
					<view class="text-red text-sm text-left paddingcontent" v-else-if="!hasSetPayPsw">*您尚未设置支付密码<text class="text-blue"
						 @tap="goPage('modifiedPayPsw')">点击设置</text></view>
					</view>
				</view>
			</view>
			<view class="flex btn-box padding bg-white">
				<button class="cu-btn btn-primary flex-sub btn-shadow" @tap="rechargeOrder">提交</button>
			</view>
			<view class="bg-white text-sm mark text-center">*最低充值金额100元</view>
		</view>
		<view v-if="basics == 1">
			<view class="orderContent bg-white">
				<view class="info">
					<view class="order-content">
						<view class="cu-bar">
							<view class="action">
								<text class="cuIcon-titles text-orange"></text>
								<text class="text-lg text-bold">充值订单信息</text>
							</view>
						</view>
						<view class="order margin-bottom">
							<view class="text-gray text-df"> <text class="label">订单金额：</text><text>{{orderInfo.money}}元</text></view>
							<view class="text-gray text-df"><text class="label">订单编号：</text><text class="">{{orderInfo.order_sn}}</text></view>
							<view class="text-gray text-df"><text class="label">创建时间：</text><text class="">{{orderInfo.create_times}}</text></view>
							<view class="line"></view>
							<view class="text-gray text-df"><text class="label">支付账户：</text><text class="">{{orderInfo.mobile}}</text></view>
							<view class="text-gray text-df flex"><text class="label">验证码：</text><input type="number" v-model="code"
								 :maxLength="6"></input><button class="cu-btn bg-orange margin-left count">{{ count }}s</button></view>
						</view>
					</view>
				</view>
			</view>
			<button class="cu-btn bg-orange lg fixed" :disabled="disabled" @tap="submitOrder">
				<text class="cuIcon-upload" v-show='disabled'></text> 确认充值</button>
		</view>
		<view v-if="basics == 2">
			<view class="orderContent bg-white">
				<view class="info">
					<image class="orderSuc" src="/static/img/orderSuc.png" mode="widthFix"></image><br>
					<text class="text-xl">充值成功</text>
					<view class="margin-bottom"></view>
					<button class="cu-btn margin-bottom bg-pink text-white margin-right-lg" @tap="goPage('project',true)">前往项目</button>
					<button class="cu-btn margin-bottom bg-white" style="border: 1rpx solid #999999; color: #999999;" @tap="goPage('balance')">前往资产</button>
					<view class="margin-bottom"></view>
				</view>
			</view>
		</view>
	</joy-page>
</template>

<script>
	import {
		mapState,
		mapGetters
	} from 'vuex'
	import mInput from '@/components/m-input/m-input.vue'
	export default {
		components: {
			mInput
		},
		computed: {
			...mapState(['forcedLogin']),
			...mapGetters(['hasSetPayPhone', 'hasSetPayPsw'])
		},
		data() {
			return {
				basicsList: [{
					cuIcon: 'radioboxfill',
					name: '充值'
				}, {
					cuIcon: 'radioboxfill',
					name: '充值订单'
				}, {
					cuIcon: 'roundcheckfill',
					name: '充值成功'
				}],
				basics: 0,
				form: {
					money: null,
					realMoney: null,
					bankName: "",
					bankId: "",
					password: ""
				},
				data: [],
				orderInfo: {},
				code: "",
				count: 180,
				timer: null,
				isError: false,
				disabled: false,
				showModal: false,
				isSelectorShow: false,
				index: 0
			};
		},
		onLoad() {
			this.rechargeBankList()
		},
		onHide(){
			clearInterval(this.timer);
		},
		methods: {
			goPage(routerName, isRoute) {
				let page = getCurrentPages()
				console.log(page)
				let redirecte = true
				if (page.length > 1) {
					if (page[page.length - 1].route.indexOf(routerName) !== -1) {
						redirecte = true
					} else {
						redirecte = false
					}
				} else {
					redirecte = false
				}
				if (redirecte) {
					this.$mRouter.back(-1)
				} else {
					if (isRoute) {
						this.$mRouter.switchTab({
							route: this.$mRoutesConfig[routerName],
						})
					} else {
						this.$mRouter.push({
							route: this.$mRoutesConfig[routerName]
						})
					}
				}
			},

			BasicsSteps() {
				this.basics = this.basics == this.basicsList.length - 1 ? 0 : this.basics + 1
			},
			PickerChange(e) {
				this.form.bankName = this.data[e.detail.value].text
				this.index = e.detail.value
				this.form.bankId = this.data[e.detail.value].value
			},
			async rechargeBankList() {
				let res = await this.$apis.rechargeBankList({
					type: 1
				});
				console.log(res)
				this.formatData(res.card_list);
			},
			formatData(data) {
				data.forEach(item => {
					let obj = {};
					obj.text = item.bank_number + "【" + item.bank_name + "】";
					obj.value = item.id;
					this.data.push(obj);
				});
				if (data.length > 0) {
					this.defaultBankId = this.data[0].value;
					this.form.bankName = this.data[0].text;
					this.form.bankId = this.data[0].value;
				}
			},
			async rechargeOrder() {
				try {
					let validate = true;
					// if (this.form.money < 100) {
					// 	validate = false;
					// 	uni.showToast({
					// 		title: '最低充值金额100元',
					// 		icon: 'none'
					// 	})
					// 	return false;
					// }
					let reg = /^[1-9]\d*$/;
					if (!reg.test(this.form.money)) {
						validate = false;
						uni.showToast({
							title: '首位数字不能为零,且为整数',
							icon: 'none'
						})
						return false;
					}
					if (this.data.length === 0) {
						validate = false;
						uni.showToast({
							title: '您尚未添加银行卡',
							icon: 'none'
						})
						return false;
					}
					if (!this.hasSetPayPhone) {
						validate = false;
						uni.showToast({
							title: '您尚未设置认证手机',
							icon: 'none'
						})
						return false;
					}
					if (!this.hasSetPayPsw) {
						validate = false;
						uni.showToast({
							title: '您尚未设置支付密码',
							icon: 'none'
						})
						return false;
					}
					this.orderInfo = await this.$apis.createRechargeOrder({
						money: this.form.money,
						bank_id: this.form.bankId,
						pay_money: this.form.realMoney,
						pay_password: this.form.password
					});
					this.getOrderInfo()
					this.BasicsSteps()
				} catch (e) {

				}

			},
			async getOrderInfo() {
				let info = await this.$apis.getRechargeOrderInfo({
					order_id: this.orderInfo.order_id,
				});
				uni.showToast({
					title: '短信验证码已发送，注意查收',
					icon: 'none'
				})
				Object.assign(this.orderInfo, info.order_info);
				if (this.orderInfo.current_time - this.orderInfo.order_time > 180) {
					this.count = 0;
				} else {
					this.count = 180 - (this.orderInfo.current_time - this.orderInfo.order_time);
					this.countdown();
				}
			},
			countdown() {
				let that = this;
				this.timer = setInterval(() => {
					if (this.count > 0) {
						this.count--;
					} else {
						clearInterval(this.timer);
						uni.showModal({
							title: "尊敬的用户：",
							content: "验证码已失效，请重新支持",
							confirmText: "重新充值",
							cancelText: "返回",
							success(res) {
								if (res.confirm) {
									that.basics = 0
								} else {
									that.back()
								}
							}
						});
					}
				}, 1000);
			},
			async submitOrder() {
				let that = this;
				try {
					if (!this.code) {
						uni.showToast({
							title: '请输入验证码',
							icon: 'none'
						})
						return false;
					}
					this.disabled = true;
					let info = await this.$apis.surePay({
						order_sn: this.orderInfo.order_sn,
						code: this.code
					});
					this.BasicsSteps()
					this.disabled = false;
				} catch (e) {
					if (err.indexOf("充值进行中") !== -1) {
						this.payAgain();
					} else {
						this.disabled = false;
						uni.showModal({
							title: "尊敬的用户：",
							content: e,
							confirmText: "重新充值",
							cancelText: "返回",
							success(res) {
								if (res.confirm) {
									that.basics = 0
								} else {
									that.back()
								}
							}
						});
					}

				}
			},
			async payAgain(err) {
				try {
					this.isPending = true;
					let that = this;
					uni.showLoading({
						title: err
					})
					let res = await this.$apis.payAgain({
						order_sn: this.orderInfo.order_sn,
					});
					if (res.status === 3) {
						uni.hideLoading()
						uni.showModal({
							title: "尊敬的用户：",
							content: e,
							confirmText: "重新充值",
							cancelText: "返回",
							success(res) {
								if (res.confirm) {
									that.basics = 0
								} else {
									that.back()
								}
							}
						});
						this.disabled = false;
					} else if (res.status === 4) {
						uni.hideLoading()
						this.BasicsSteps()
						this.disabled = false;
					} else {
						setTimeout(() => {
							this.payAgain("充值进行中,请耐心等待");
						}, 5000)
					}
				} catch (e) {
					uni.hideLoading()
					uni.showModal({
						title: "尊敬的用户：",
						content: e,
						confirmText: "重新充值",
						cancelText: "返回",
						success(res) {
							if (res.confirm) {
								that.basics = 0
							} else {
								that.back()
							}
						}
					});
					this.disabled = false;
				}
			},

			back() {
				let page = getCurrentPages()
				if (page.length > 1) {
					this.$mRouter.back()
				} else {
					this.$mRouter.push({
						route: this.$mRoutesConfig.balanceDetail,
					})
				}

			}
		},
		watch: {
			"form.money": function(value) {
				let money = parseFloat(value);
				if (money < 200) {
					this.form.realMoney = money + 1;
				} else {
					this.form.realMoney = (money + money * 0.005).toFixed(2);
				}
			}
		},
	}
</script>

<style lang="scss" scoped>
	.text-invalid{
		color: #FFB89A;
	}
	.bg-gray{
		background:rgba(247,247,247,1);
	}

	.step-text {
		font-size: 22rpx;
		font-family: PingFang SC;
		font-weight: 500;
	}

	.cu-steps .cu-item [class*="cuIcon-"],
	.cu-steps .cu-item .num {
		line-height: 50rpx;
	}

	.cu-steps .cu-item:before,
	.cu-steps .cu-item:after,
	.cu-steps.steps-arrow .cu-item:before,
	.cu-steps.steps-arrow .cu-item:after {
		top: 25rpx;
	}

	.orderContent {
		width: 100%;
		margin: 0 auto;
		overflow: hidden;
		font-size: 0;
		text-align: center;

		image {
			width: 100%;
			font-size: 0;
		}

		.orderSuc {
			margin-top: 36rpx;
			margin-bottom: 47rpx;
			width: 302rpx;
			font-size: 0;
		}
	}

	.info {
		.text-nor {
			display: block;
			margin-top: 18rpx;
			margin-bottom: 30rpx;
		}

		.balance {
			text-align: left;
			margin: 60rpx 0 80rpx;
		}

		.mark {
			padding: 20rpx 0;
		}

		.order-content {
			padding: 0 52rpx;
		}
	}

	.share {
		margin: 156rpx 0 64rpx;
	}

	.fixed {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		border-radius: 0;
	}

	.label {
		width: 152rpx;
		line-height: 60rpx;
		display: inline-block;
	}

	.order {
		text-align: left;

		.text-gray {
			color: #646464;
		}
	}

	.line {
		width: 100%;
		height: 1px;
		background-color: #E6E6E6;
		margin: 17rpx 0;
	}

	.cu-bar .action:first-child {
		margin-left: 0
	}

	input {
		border: 1px solid #B6B6B6;
		border-radius: 10px;
		padding: 0 20rpx;
		height: 64rpx;
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 500;
	}

	.count {
		border-radius: 10px;
		font-size: 24rpx;
		border: 1px solid rgba(255, 106, 0, 1);
	}

	.tips {
		font-size: 24rpx;
		font-family: PingFang SC;
		text-align: center;
		// background: rgba(255, 241, 230, 1);

		.cuIcon-notificationfill {
			margin-right: 20rpx;
		}
	}

	.cu-form-group {
		border-bottom: 1rpx solid #EEEEEE;
		margin: 0 52rpx;
		padding: 0;

		.title {
			font-size: 24rpx;
		}
	}

	.paddingcontent {
		padding: 30rpx 52rpx;
	}
</style>
